<?php
	/**
	 * Elgg product - edit action
	 * 
	 * @package Elgg SocialCommerce
	 * @license http://www.gnu.org/licenses/old-licenses/gpl-2.0.html GNU Public License version 2
	 * @author Cubet Technologies
	 * @copyright Cubet Technologies 2009-2010
	 * @link http://elgghub.com/
	 **/

	global $CONFIG;
	$CONFIG->pluginlistcache = null;
	//----------- Get variables ---------------//
	$title = trim(get_input("storestitle"));
	$desc = trim(get_input("storesbody"));
	$file_name = trim($_FILES['upload']['name']);
	$product_type_id = get_input("product_type_id");
	$category = get_input("storescategory");
	$tags = trim(get_input("storestags"));
	$access_id = (int) get_input("access_id");
	$guid = (int) get_input('stores_guid');
	$tax_country = trim(get_input("tax_country"));
	$price = get_input('price');
	$units = get_input('units');
	$date_from = get_input('date_from');
	$date_until = get_input('date_until');
	$image_title = get_input('image_title');
	
	//---------------- Check the entity --------------//
	if (!$stores = get_entity($guid)) {
		register_error(elgg_echo("stores:uploadfailed"));
		forward($CONFIG->wwwroot . "pg/{$CONFIG->pluginname}/" . $_SESSION['user']->username);
		exit;
	}
	
	//specific number cos product ID doesn't exist anymore
	$product_fields = $CONFIG->product_fields[2];
	
	//------------ Validation --------------------//
	if(empty($title)){
		$error_field = ", ".elgg_echo("title");
	}
	if(empty($desc)){
		$error_field .= ", ".elgg_echo("stores:text");
	}
	/*
	if(empty($product_type_id) || $product_type_id <= 0){
		$error_field .= ", ".elgg_echo("product:type");
	}*/
	if(empty($category)){
		$error_field .= ", ".elgg_echo("Category");
	}
	
	if (is_array($product_fields) && sizeof($product_fields) > 0){
		foreach ($product_fields as $shortname => $valtype){
			if($valtype['mandatory'] == 1){
				$value = trim(get_input($shortname));
				if($valtype['field'] == 'file')
					$value = trim($_FILES[$shortname]['name']);
				if(empty($value)){
					if($valtype['field'] == 'file' && $shortname == 'upload'){
						if($stores->mimetype == "")
							$error_field .= ", ".elgg_echo("product:".$shortname);
					}else{
						$error_field .= ", ".elgg_echo("product:".$shortname);
					}
				}else{
					if($shortname == 'quantity'){
						if(ereg("[^0-9]",$value))
							$error_field .= ", ".elgg_echo("product:".$shortname);
					}
					if($shortname == 'base_stock'){
						if(ereg("[^0-9]",$value))
							$error_field .= ", ".elgg_echo("product:".$shortname);
					}
					if($shortname == 'price'){
						if(!is_numeric($value) || $value == 0)
							$error_field .= ", ".elgg_echo("product:".$shortname);
							
					}
				}
			}
		}
	}
	// why product type id?
	$validation = elgg_view("custom_field/validation",array('entity_type'=>$product_type_id));
	if($validation){
		$error_field .= ", ".$validation;
	}
	
	$result = false;
	
	$container_guid = $stores->container_guid;
	$container = get_entity($container_guid);
	
	if(!empty($error_field)){
		unset($_SESSION['product']);
		$_SESSION['product']['storestitle'] = $title;
		$_SESSION['product']['storesbody'] = $desc;
		$_SESSION['product']['product_type_id'] = $product_type_id;
		$_SESSION['product']['storescategory'] = $category;
		$_SESSION['product']['units'] = $units;
		$_SESSION['product']['storestags'] = $tags;
		$_SESSION['product']['access_id'] = $access_id;
		$_SESSION['product']['date_from']= $date_from;
		$_SESSION['product']['date_until']= $date_until;
		
		if (is_array($product_fields) && sizeof($product_fields) > 0){
			foreach ($product_fields as $shortname => $valtype){
				if($valtype['field'] != 'file')
					$_SESSION['product'][$shortname] = get_input($shortname);
			}
		}
		
		$error_field = substr($error_field,2);
		
		register_error(sprintf(elgg_echo("product:validation:null"),$error_field));
		$container_user = get_entity($container_guid);
		$redirect = $CONFIG->wwwroot . "mod/{$CONFIG->pluginname}/edit.php?stores_guid=".$guid;
	}else{
		if ($stores->canEdit()) {
			$old_product_type_id = $stores->product_type_id;
			$old_product_fields = $CONFIG->product_fields[$old_product_type_id];
			if($old_product_type_id != $product_type_id && is_array($old_product_fields) && sizeof($old_product_fields) > 0){
				foreach ($old_product_fields as $old_shortname => $old_valtype){
					if($old_valtype['field'] == 'file' && $old_shortname == 'upload'){
						$stores->filename = "";
						$stores->mimetype = "";
						$stores->originalfilename = "";
					}else{
						$stores->$old_shortname = "";
					}
				}
			}
			if (is_array($product_fields) && sizeof($product_fields) > 0){
				foreach ($product_fields as $shortname => $valtype){
					/*
					if($valtype['field'] == 'file' && $shortname == 'upload' && isset($_FILES[$shortname]) && $_FILES[$shortname]['name'] != ""){
						$old_filehandler = new ElggFile();
						$old_filehandler->owner_guid = $stores->owner_guid;
						$old_filehandler->setFilename($stores->filename);
						$old_file = $old_filehandler->getFilenameOnFilestore();
						if (substr_count($stores->mimetype,'image/')){
							$old_filehandler->setFilename($stores->thumbnail);
							$old_thumbnail_file = $old_filehandler->getFilenameOnFilestore();
							$old_filehandler->setFilename($stores->smallthumb);
							$old_smallthumb_file = $old_filehandler->getFilenameOnFilestore();
							$old_filehandler->setFilename($stores->largethumb);
							$old_largethumb_file = $old_filehandler->getFilenameOnFilestore();
						}
						
						$prefix = "{$CONFIG->pluginname}/";
						$upload_file = new ElggFile();
						$filestorename = strtolower(time().$_FILES[$shortname]['name']);
						$upload_file->setFilename($prefix.$filestorename);
						$upload_file->setMimeType($_FILES[$shortname]['type']);
						$upload_file->originalfilename = $_FILES[$shortname]['name'];
						$upload_file->open("write");
						$upload_file->write(get_uploaded_file('upload'));
						$upload_file->close();
						
						$stores->filename = $upload_file->filename;
						$stores->mimetype = $upload_file->mimetype;
						$stores->originalfilename = $upload_file->originalfilename;
						$stores->simpletype = get_general_product_type($_FILES[$shortname]['type']);
					}else{
						*/
					
					$value = trim(get_input($shortname));
					if(!empty($value))
						$stores->$shortname = trim(get_input($shortname));
					
						
					
				}
			}
			
			//get the old image array
			$old_images = unserialize($stores->images);
			$x=0;
			foreach ($old_images as $old_image){
				if($old_image['path']==$image_title){
					$old_images[$x]['order']="1";
				}
				else{
					$old_images[$x]['order']="2";
				}
				$x++;
			}
		//	$stores->blahblah - ""
			$stores->access_id = $access_id;
			$stores->title = $title;
			$stores->description = $desc;
			$stores->product_type_id = $product_type_id;
			$stores->category = $category;
			$stores->countrycode = $tax_country;
			//$stores->units = $units;
			$stores->date_until = $date_until;
			$stores->date_from = $date_from;
			
			
			// Save tags
			$tags = explode(",", $tags);
			$stores->tags = $tags;
			
			$files = array();
		    $x = 0;
		    
		    foreach ($_FILES as $key => $value) {
		        if ((!is_null($value)) && ($value !== "")) {
		            $files[$x] = $value;
		            $x++;
					//echo " value is ".$files[$x].", ";
		        }
		    }			
			
		    $num_files = count($files[0]['tmp_name']);
		    
		
			
			$images = array();
				 for ($i = 0; $i < $num_files - 1; $i++) {
			        
			        $temp_file = $files[0]['tmp_name'][$i];
			        $filename = $files[0]['name'][$i];
					$name = $files[0]['name'][$i];
   			 
					$image_ind = $i + count($old_images) + 1;
					$image_prefix = $CONFIG->pluginname."/".$guid."/".$image_ind;
					
				 	if($image_ind==($image_title)){
			        	$order = "1";
			        }
			        else{
			        	$order = "2";
			        }						
					
					$new_image = array('path' => "$image_ind", 'order' => "$order");
					$images[] = $new_image;
								
					
					$product_imagehandler = new ElggFile();
					$product_imagehandler->owner_guid = $stores->owner_guid;
					$product_imagehandler->setFilename($image_prefix . ".jpg");
					$product_imagehandler->open("write");
					$product_imagehandler->write(file_get_contents($temp_file));
					$product_imagehandler->close();
					
					$product_thumbtiny = get_resized_image_from_existing_file($product_imagehandler->getFilenameOnFilestore(),25,25, true);
					$product_thumbsmall = get_resized_image_from_existing_file($product_imagehandler->getFilenameOnFilestore(),40,40, true);
					$product_thumbmedium = get_resized_image_from_existing_file($product_imagehandler->getFilenameOnFilestore(),100,100, true);
					$product_thumblarge = get_resized_image_from_existing_file($product_imagehandler->getFilenameOnFilestore(),350,800, true);
					if ($product_thumbtiny) {
						
						$product_thumb = new ElggFile();
						$product_thumb->owner_guid = $stores->owner_guid;
						$product_thumb->setMimeType('image/jpeg');
						
						$product_thumb->setFilename($image_prefix."tiny.jpg");
						$product_thumb->open("write");
						$product_thumb->write($product_thumbtiny);
						$product_thumb->close();
						
						$product_thumb->setFilename($image_prefix."small.jpg");
						$product_thumb->open("write");
						$product_thumb->write($product_thumbsmall);
						$product_thumb->close();
						
						$product_thumb->setFilename($image_prefix."medium.jpg");
						$product_thumb->open("write");
						$product_thumb->write($product_thumbmedium);
						$product_thumb->close();
						
						$product_thumb->setFilename($image_prefix."large.jpg");
						$product_thumb->open("write");
						$product_thumb->write($product_thumblarge);
						$product_thumb->close();
						
						
							
					}
				 }
				$new_images = array_merge($old_images, $images);
				$stores->images = serialize($new_images);
				$stores->icontime = time();
				$stored = $stores->save();
		}	
		
		if($stored){
				system_message(elgg_echo("stores:saved"));
				unset($_SESSION['product']);
		}
		else{
			register_error(elgg_echo("stores:uploadfailed"));
		}
		$container_user = get_entity($container_guid);	
		$redirect = $CONFIG->wwwroot . "pg/{$CONFIG->pluginname}/" . $container_user->username;
	}
	forward($redirect);
?>
